import Icon from "@/components/Icon";
import { getUserProfile } from "@/store/actions/profile";
import useInitialState from "@/utils/use-initial-state";
import { NavBar, Input, Toast } from "antd-mobile";
import { useEffect, useRef, useState } from "react";
import { useHistory } from "react-router-dom";
import styles from "./index.module.scss";
import { io, Socket } from "socket.io-client";
import { getToken } from "@/utils/storage";
function ChatIndex() {
  const history = useHistory();
  const [messageList, setMessageList] = useState<
    {
      type: "robot" | "user";
      text: string;
    }[]
  >([
    { type: "robot", text: "亲爱的用户您好，小智同学为您服务。" },
    { type: "user", text: "你好" },
  ]);
  const { userProfile } = useInitialState(getUserProfile, "profile");

  // 输入框中的数据
  const [message, setMessage] = useState("");
  // 用户发送数据
  const onSendMessage = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      if (message.trim() === "") {
        return Toast.show({
          icon: "fail",
          content: "请输入内容",
        });
      }
      // 通过socket.io 客户端向服务端发送信息
      clientRef.current?.emit("message", {
        msg: message,
        timestamp: Date.now(),
      });
      // 向聊天记录中添加当前发送的消息
      setMessageList((messageList) => [
        ...messageList,
        {
          type: "user",
          text: message,
        },
      ]);
      // 发送完之后清空输入框、
      setMessage("");
    }
  };
  //! socket通讯
  // 用于缓存 socket.io 客户端实例
  const clientRef = useRef<Socket | null>(null);
  // 和服务器建立了链接
  useEffect(() => {
    // 创建客户端实例
    const client = io("http://toutiao.itheima.net", {
      transports: ["websocket"],
      // 在查询字符串中传递token
      query: {
        token: getToken().token,
      },
    });
    // 监听连接成功的事件
    client.on("connect", () => {
      setMessageList((messageList) => {
        return [
          ...messageList,
          {
            type: "robot",
            text: "9527为您服务",
          },
        ];
      });
    });
    // 监听收到消息的事件
    client.on("message", (data) => {
      console.log("收到信息", data);
      // 收到消息的话向聊天记录里添加机器人回复的消息
      setMessageList((messageList) => [
        ...messageList,
        {
          type: "robot",
          text: data.msg,
        },
      ]);
    });
    // 将客户端实例缓存到ref引用中
    clientRef.current = client;

    // 在组件销毁时关闭 socket.io 的连接
    return () => {
      client.close();
    };
  }, []);
  const chatListRef = useRef<HTMLDivElement>(null);

  // 监听聊天数据的变化，改变聊天容器元素的 scrollTop 值让页面滚到最底部
  useEffect(() => {
    const current = chatListRef.current!;
    current.scrollTop = current.scrollHeight;
  }, [messageList]);
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="fixed-header" onBack={() => history.go(-1)}>
        小智同学
      </NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list" ref={chatListRef}>
        {/* 机器人的消息 */}

        {messageList.map((msg, index) => {
          // 机器人的消息
          if (msg.type === "robot") {
            return (
              <div className="chat-item" key={index}>
                <Icon type="icon-kefu" />
                <div className="message">{msg.text}</div>
              </div>
            );
          } else {
            // 用户的消息
            return (
              <div className="chat-item user" key={index}>
                <img src={userProfile.photo} alt="" />
                <div className="message">{msg.text}</div>
              </div>
            );
          }
        })}
      </div>

      {/* 底部消息输入框 */}
      <div className="input-footer">
        <Input className="no-border" placeholder="请描述您的问题" value={message} onChange={(e) => setMessage(e)} onKeyUp={(e) => onSendMessage(e)} />
        <Icon type="iconbianji" />
      </div>
    </div>
  );
}

export default ChatIndex;
